package com.fc.mall.portal.service.impl;

import com.fc.mall.base.object.Result;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.mapper.*;
import com.fc.mall.model.*;
import com.fc.mall.portal.domain.*;
import com.fc.mall.mapper.*;
import com.fc.mall.portal.domain.*;
import com.fc.mall.portal.dto.BargainInfo;
import com.fc.mall.portal.dto.OmsBargainCartItem;
import com.fc.mall.portal.service.*;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.util.Utils;
import com.fc.mall.model.*;
import com.fc.mall.portal.service.*;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by sunny on 2019/9/10.
 */
@Service
public class OmsBargainServiceImpl implements OmsBargainService {

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private OmsBargainMapper bargainMapper;

    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private PmsProductBargainMapper productBargainMapper;

    @Autowired
    private OmsBargainListMapper bargainListMapper;

    @Autowired
    private UmsMemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    private OmsPortalOrderService portalOrderService;

    @Autowired
    private OmsOrderMapper orderMapper;

    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;

    @Autowired
    private SmsService smsService;

    @Override
    public OmsBargain createBargain(BargainParam bargainParam) {
        UmsMember currentMember = memberService.getCurrentMember();
        PmsProductBargain productBargain = productBargainMapper.selectByPrimaryKey(bargainParam.getProductBargainId());
        if(null == productBargain)
        {
            throw new ServiceException("砍价商品已下架");
        }
        OmsBargain bargain = new OmsBargain();
        mapperFacade.map(bargainParam, bargain);
        bargain.setOwnerId(currentMember.getId().intValue());
        bargain.setNickname(currentMember.getNickname());
        bargain.setPic(bargainParam.getProductPic());
        bargain.setIcon(currentMember.getIcon());
        bargain.setDealMoney(bargainParam.getPrice());
        bargain.setOriginalMoney(bargainParam.getPrice());
        bargain.setCreateTime(new Date());
        bargain.setSkuId(bargainParam.getProductSkuId());
        Long expiredMills = System.currentTimeMillis()/1000 + productBargain.getActiveMin()*60;
        bargain.setExpiredTime(DateTimeHelper.getDateFromEpochTimeInSecond(expiredMills));
        bargainMapper.insertSelective(bargain);
        return bargain;
    }

    @Override
    public BargainInfo getBargainById(Long bargainId) {
        UmsMember currentMember = memberService.getCurrentMember();
        BargainInfo bargainInfo = new BargainInfo();
        OmsBargain omsBargain = bargainMapper.selectByPrimaryKey(bargainId);
        mapperFacade.map(omsBargain, bargainInfo);
        PmsProductBargain pmsProductBargain =  productBargainMapper.selectByPrimaryKey(omsBargain.getProductBargainId());
        OmsBargainListExample bargainListExample = new OmsBargainListExample();
        bargainListExample.createCriteria().andBargainIdEqualTo(bargainId.intValue());
        List<OmsBargainList> friendsList =  bargainListMapper.selectByExample(bargainListExample);
        bargainInfo.setOwner(currentMember.getId().intValue() == omsBargain.getOwnerId().intValue());
        if(!friendsList.isEmpty())
        {
           friendsList.stream().forEach(friend -> {
               friend.setNickname(Utils.urlDecoderTransfer(friend.getNickname()));
           });
           boolean hasBargain = friendsList.stream().filter(friend -> friend.getAssistorId().equals(currentMember.getId())).collect(Collectors.toList()).size() > 0;
           bargainInfo.setSelfBargain(hasBargain);
        }

        bargainInfo.setBargainFriendList(friendsList);
        bargainInfo.setActivityMoney(pmsProductBargain.getActivityPrice());
        bargainInfo.setOriginalCount(pmsProductBargain.getJoinCount().intValue());
        bargainInfo.setNickname(Utils.urlDecoderTransfer(bargainInfo.getNickname()));
        if(DateTimeHelper.getCurrentDateFromZero().after(bargainInfo.getExpiredTime())
                || omsBargain.getBargainCount() >= pmsProductBargain.getJoinCount()
                || omsBargain.getOrderId() != null)
        {
            bargainInfo.setStatus(1);
        }
        else
        {
            bargainInfo.setStatus(0);
        }

        return bargainInfo;
    }

    @Override
    @Transactional
    public OmsBargainList friendBargain(Long bargainId) {

        UmsMember currentMember = memberService.getCurrentMember();
        OmsBargain omsBargain = bargainMapper.selectByPrimaryKey(bargainId);

        if(null == omsBargain)
        {
            throw new ServiceException(String.format("当前砍价不存在{{%s}}", bargainId));
        }

        PmsProductBargain pmsProductBargain =  productBargainMapper.selectByPrimaryKey(omsBargain.getProductBargainId());
        if(omsBargain.getOrderId() != null
                || omsBargain.getBargainCount().equals(pmsProductBargain.getJoinCount())
                || DateTimeHelper.getEpochTimeInSecond(omsBargain.getExpiredTime()) < DateTimeHelper.getEpochTimeInSecond(System.currentTimeMillis())
                )
        {
            throw new ServiceException("砍价已结束");
        }

        int prvDealPrice = omsBargain.getDealMoney().multiply(new BigDecimal(100)).intValue();
        int activityPrice = pmsProductBargain.getActivityPrice().multiply(new BigDecimal(100)).intValue();
        int currentBargainCount = omsBargain.getBargainCount().intValue() + 1;
        int cutPrice = 0;
        if(currentBargainCount < pmsProductBargain.getJoinCount().intValue())
        {
            cutPrice = Utils.getRandom(0, prvDealPrice - activityPrice);
        }
        else
        {
            cutPrice = prvDealPrice - activityPrice;
        }
        omsBargain.setDealMoney(new BigDecimal(prvDealPrice -cutPrice).divide(new BigDecimal(100)));
        omsBargain.setBargainCount(currentBargainCount);
        bargainMapper.updateByPrimaryKey(omsBargain);

        OmsBargainList bargainList = OmsBargainList.builder()
                .bargainId(bargainId)
                .bargainMoney(new BigDecimal(cutPrice).divide(new BigDecimal(100)))
                .nickname(currentMember.getNickname())
                .icon(currentMember.getIcon())
                .assistorId(currentMember.getId())
                .createTime(new Date()).build();

        bargainListMapper.insertSelective(bargainList);

        //好友帮忙砍价发送消息
        friendBargainNotice(omsBargain, pmsProductBargain, cutPrice);

        return bargainList;
    }

    @Override
    public List<BargainInfo> getBargainListOfSelf(BargainQueryParam bargainParam) {
        UmsMember currentMember = memberService.getCurrentMember();
        OmsBargainExample bargainExample = new OmsBargainExample();
        bargainExample.createCriteria().andOwnerIdEqualTo(currentMember.getId()).andIsAddorderEqualTo(bargainParam.getIsAddOrder());

        List<OmsBargain> bargainList =  bargainMapper.selectByExample(bargainExample);
        List<BargainInfo>  bargainInfoList = mapperFacade.mapAsList(bargainList, BargainInfo.class);
        bargainInfoList.stream().forEach(v -> {
            v.setStatus(bargainParam.getIsAddOrder());
        });
        return bargainInfoList;
    }

    @Override
    public ConfirmOrderResult generateConfirmBargainOrder(OmsBargainCartItem bargainCartItem) {
        ConfirmOrderResult orderResult = new ConfirmOrderResult();

        if(null != bargainCartItem.getBargainId())
        {
            orderResult.setBargainId(bargainCartItem.getBargainId());
        }

        CartPromotionItem promotionItem = new CartPromotionItem();
        mapperFacade.map(bargainCartItem, promotionItem);
        List<CartPromotionItem> itemList = new ArrayList<>();
        itemList.add(promotionItem);
        orderResult.setCartPromotionItemList(itemList);
        List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
        orderResult.setMemberReceiveAddressList(memberReceiveAddressList);

        ConfirmOrderResult.CalcAmount calcAmount = OmsOrderGroupServiceImpl.calcCartAmount(promotionItem);
        orderResult.setCalcAmount(calcAmount);
        return orderResult;
    }

    @Override
    public Result generateBargainOrder(ImmediatelyBargainOrderParam immediatelyOrderParam) {

        OmsBargainCartItem bargainCartItem = immediatelyOrderParam.getOmsCartItem();
        OrderParam orderParam = immediatelyOrderParam.getOrderParam();

        UmsMember currentMember = memberService.getCurrentMember();


        OmsBargain bargain = bargainMapper.selectByPrimaryKey(bargainCartItem.getBargainId());

        if(null == bargain)
        {
            throw new ServiceException("当前砍价不存在");
        }

        OmsOrderItem orderItem = OmsOrderItem.builder()
                .productId(bargainCartItem.getProductId())
                .productName(bargainCartItem.getProductName())
                .productPic(bargainCartItem.getProductPic())
                .productAttr(bargainCartItem.getProductAttr())
                .productPrice(bargainCartItem.getPrice())
                .productQuantity(bargainCartItem.getQuantity())
                .productSkuId(bargainCartItem.getProductSkuId())
                .promotionAmount(new BigDecimal(0.00))
                .promotionName("砍价")
                .giftIntegration(0)
                .giftGrowth(0)
                .sp1(bargainCartItem.getSp1())
                .sp2(bargainCartItem.getSp2())
                .build();

        BigDecimal totalAmount = orderItem.getProductPrice().multiply(new BigDecimal(orderItem.getProductQuantity())).setScale(2);
        OmsOrder order = buildBargainOrder(currentMember, orderParam, totalAmount);
        //插入order表和order_item表
        orderMapper.insert(order);
        orderItem.setOrderId(order.getId());
        orderItem.setOrderSn(order.getOrderSn());
        omsOrderItemMapper.insert(orderItem);
        Map<String,Object> result = new HashMap<>();
        bargain.setOrderId(order.getId());
        // isAddOrder: 0 -> 未订单  1 -> 已下单
        bargain.setIsAddorder(1);
        bargainMapper.updateByPrimaryKeySelective(bargain);
        result.put("order",order);
        result.put("bargainId", bargainCartItem.getId());
        return Result.success("下单成功", result);
    }


    /**
     * 好友帮忙砍价发送消息
     * @param omsBargain
     * @param pmsProductBargain
     * @param cutPrice
     */
    private void friendBargainNotice(OmsBargain omsBargain, PmsProductBargain pmsProductBargain, int cutPrice){
        int currentBargainCount = omsBargain.getBargainCount().intValue();

        String inprogessDesc = "已有" + omsBargain.getBargainCount() + "人砍价";
        String cutPriceString = new BigDecimal(cutPrice).divide(new BigDecimal(100)).setScale(2).toString() + "元";
        String minPrice = pmsProductBargain.getActivityPrice().setScale(2).toString() + "元";
        String tipMsg = "留给你的时间不多了，快召集好友吧！";
        if (currentBargainCount == pmsProductBargain.getJoinCount().intValue()){
            tipMsg = "砍价成功！";
        }
        smsService.sendBargainInprogessNotice(
                omsBargain.getOwnerId().longValue(),
                omsBargain.getProductName(),
                inprogessDesc,
                cutPriceString,
                minPrice,
                DateTimeHelper.getStringFromDate(omsBargain.getExpiredTime(), DateTimeHelper.SQL_DATETIME),
                tipMsg);
    }

    private OmsOrder buildBargainOrder(UmsMember currentMember, OrderParam orderParam, BigDecimal totalAmount)
    {
        OmsOrder order = OmsOrder.builder()
                .discountAmount(new BigDecimal(0))
                .build();
        order.setTotalAmount(totalAmount);
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(new BigDecimal(0));
        order.setPromotionInfo("砍价优惠");
        order.setCouponAmount(new BigDecimal(0));
        order.setIntegration(0);
        order.setIntegrationAmount(new BigDecimal(0));

        order.setPayAmount(totalAmount);
        //转化为订单信息并插入数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        String nickName = StringUtils.isEmpty(currentMember.getNickname()) ? "" : currentMember.getNickname();
        try {
            order.setMemberUsername(URLEncoder.encode(nickName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(2);
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(1);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->团购订单；2 -> 砍价订单
        order.setOrderType(2);
        //收货人信息：姓名、电话、邮编、地址
        UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        order.setNote(orderParam.getContent());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        //计算赠送积分
        order.setIntegration(0);
        //计算赠送成长值
        order.setGrowth(0);
        //生成订单号
        order.setOrderSn(portalOrderService.generateOrderSn(order));
        return order;
    }






}
